package com.drawables;

import javax.microedition.khronos.opengles.GL10;

import android.util.Log;

import com.interfaces.AybivedDrawable;
import com.interfaces.Updateable;

public class Animation extends AybivedDrawable implements Updateable {
	private String name;
	private boolean isPlaying = true;
	private int framerate = 60;
	private double frametime = 0;
	private int currentFrame = 0;
	private boolean isVisible = true;
	public float posY, posX;
	
	public Animation( String name, int sprites, float posX, float posY ) {
		super();
			try{
			for( int i=0; i<sprites; i++)
			{
				String enumeration;
				if(i < 9)
					enumeration = "000" + String.valueOf(i+1);
				else
					enumeration = "00" + String.valueOf(i+1);
				
				String identifier = "com.aybived:drawable/" + name + enumeration;
				addBitmap(identifier);
			}
			}
			catch( Exception e)
			{
				Log.e("exception in animation", e.getMessage());
			}
		this.posX = posX;
		this.posY = posY;
		this.name = name;
	}
	
	@Override
	public void draw(GL10 gl) {
		if( isVisible)
		{
			gl.glPushMatrix();
				gl.glTranslatef( posX, posY, 0 );
				gl.glEnable(GL10.GL_BLEND);
				gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
				gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
				gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, UVBuffer);
				gl.glBindTexture( GL10.GL_TEXTURE_2D, texIDs.get(currentFrame) );
				gl.glFrontFace(GL10.GL_CCW);
				gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertexBuffer);
				gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
				gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, vertices.length / 3);
				gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
				gl.glDisable(GL10.GL_BLEND);
			gl.glPopMatrix();
		}
	}

	@Override
	public void update(double dt) {
		//if(!isVisible || isOutofBounds())
			//return;
		//posX -= (float)(AybivedConfig.GAME_SCROLL_SPEED * dt);
		
		if(isPlaying)
		{
			frametime += dt;
			//checking how much time has been passed
			//if frame time has been passed reset timer and increase frame count
			if( frametime >= ( 1.0f / framerate))
			{
				frametime -= ( 1.0f / framerate);
				++currentFrame;
				if( currentFrame >= getTextureCount()) //reset counter on reaching animation end
					currentFrame = 0;
			}
		}
	}
	
	public void play()
	{
		isPlaying = true;
	}
	
	public void stop()
	{
		isPlaying = false;
	}
	
	public boolean isPlaying()
	{
		return isPlaying;
	}
	
	public void setFrameRate( int fps )
	{
		framerate = fps;
	}
	
	String getAnimationName()
	{
		return name;
	}
	
	public boolean isOutofBounds()
	{
		if(posX < -getTextureWidth())
			return true;
		return false;
	}
	
	public void setVisible(boolean flag)
	{
		isVisible = flag;
	}
}
